<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  

  
  <title>搞定Python装饰器（二） | Laomo 的后院</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="对象型装饰器上一篇文章讲了如何编写一个函数型装饰器，这篇文章我们来讲讲如何编写一个类或者对象型的装饰器。 之前说过，装饰器要是一个可调用对象，所以说当我们想用对象作为一个装饰器时，只需要实现__call__方法即可。 接下来，我们来修改timeit，实现一类两用。timeit本质上是一个timer，timer可以作为计时器使用，但timer对象作为装饰器使用时，可以为函数进行计时。 1234567">
<meta property="og:type" content="article">
<meta property="og:title" content="搞定Python装饰器（二）">
<meta property="og:url" content="http://yoursite.com/2020/04/04/%E6%90%9E%E5%AE%9APython%E8%A3%85%E9%A5%B0%E5%99%A8%EF%BC%88%E4%BA%8C%EF%BC%89/index.html">
<meta property="og:site_name" content="Laomo 的后院">
<meta property="og:description" content="对象型装饰器上一篇文章讲了如何编写一个函数型装饰器，这篇文章我们来讲讲如何编写一个类或者对象型的装饰器。 之前说过，装饰器要是一个可调用对象，所以说当我们想用对象作为一个装饰器时，只需要实现__call__方法即可。 接下来，我们来修改timeit，实现一类两用。timeit本质上是一个timer，timer可以作为计时器使用，但timer对象作为装饰器使用时，可以为函数进行计时。 1234567">
<meta property="article:published_time" content="2020-04-04T01:25:17.000Z">
<meta property="article:modified_time" content="2020-04-09T15:07:27.891Z">
<meta property="article:author" content="Laomo.">
<meta property="article:tag" content="python教程">
<meta name="twitter:card" content="summary">
  
    <link rel="alternate" href="/atom.xml" title="Laomo 的后院" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  
<link rel="stylesheet" href="/css/style.css">

<meta name="generator" content="Hexo 4.2.0"></head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">Laomo 的后院</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://yoursite.com"></form>
      </div>
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main"><article id="post-搞定Python装饰器（二）" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2020/04/04/%E6%90%9E%E5%AE%9APython%E8%A3%85%E9%A5%B0%E5%99%A8%EF%BC%88%E4%BA%8C%EF%BC%89/" class="article-date">
  <time datetime="2020-04-04T01:25:17.000Z" itemprop="datePublished">2020-04-04</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      搞定Python装饰器（二）
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="对象型装饰器"><a href="#对象型装饰器" class="headerlink" title="对象型装饰器"></a>对象型装饰器</h2><p>上一篇文章讲了如何编写一个函数型装饰器，这篇文章我们来讲讲如何编写一个类或者对象型的装饰器。</p>
<p>之前说过，装饰器要是一个可调用对象，所以说当我们想用对象作为一个装饰器时，只需要实现<code>__call__</code>方法即可。</p>
<p>接下来，我们来修改timeit，实现一类两用。timeit本质上是一个timer，timer可以作为计时器使用，但timer对象作为装饰器使用时，可以为函数进行计时。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># mytimer.py</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Timer</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        self.__start = <span class="number">0</span></span><br><span class="line">        self.__last = <span class="number">0</span></span><br><span class="line"></span><br><span class="line">        self.__started = <span class="literal">False</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">start</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> self.__started:</span><br><span class="line">            self.__start = time.time()</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">raise</span> Exception(<span class="string">'Timer has been started'</span>)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">stop</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">if</span> self.__started:</span><br><span class="line">            self.last = self.__start - time.time()</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">raise</span> Exception(<span class="string">'Timer is not running.'</span>)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">last_time</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> self.__started:</span><br><span class="line">            <span class="keyword">return</span> self.__last</span><br><span class="line">        <span class="keyword">return</span> time.time() - self.__start</span><br></pre></td></tr></table></figure>
<p>这是一个简单计时器的基本逻辑，现在我们来实现<code>__call__</code>方法。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Timer</span>:</span></span><br><span class="line">    <span class="comment"># ....</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__call__</span><span class="params">(self, func)</span>:</span></span><br><span class="line">        <span class="function"><span class="keyword">def</span> <span class="title">wrapper</span><span class="params">(*args, **kwargs)</span>:</span></span><br><span class="line">            start = time.time() * <span class="number">1000</span></span><br><span class="line"></span><br><span class="line">            <span class="keyword">try</span>:</span><br><span class="line">                rtn = func(*args, **kwargs)</span><br><span class="line">            <span class="keyword">except</span>:</span><br><span class="line">                <span class="keyword">raise</span></span><br><span class="line">            <span class="keyword">finally</span>:</span><br><span class="line">                print(<span class="string">'[ time = %s ms ]'</span> %</span><br><span class="line">                        (time.time() * <span class="number">1000</span> - start))</span><br><span class="line">            <span class="keyword">return</span> rtn</span><br><span class="line">        <span class="keyword">return</span> wrapper</span><br><span class="line">    <span class="comment"># ....</span></span><br></pre></td></tr></table></figure>

<p>由于实现了<code>__call__</code>方法，我们的对象可以像函数一样被调用了。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># test_obj.py</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> mytimer <span class="keyword">import</span> Timer</span><br><span class="line"></span><br><span class="line">timeit = Timer()</span><br><span class="line"></span><br><span class="line"><span class="meta">@timeit</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">foo</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="keyword">for</span> _ <span class="keyword">in</span> range(<span class="number">5013</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># foo = timeit(foo)</span></span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$ python test_obj.py</span><br><span class="line">[ time &#x3D; 1.08 ms ]</span><br></pre></td></tr></table></figure>

<h2 id="类对象装饰器"><a href="#类对象装饰器" class="headerlink" title="类对象装饰器"></a>类对象装饰器</h2><p>python中，类也可以作为装饰器使用，由于object类的元类(metaclass)已经帮我们实现了<code>__call__</code>方法，所以我们只需要在我们类中的<code>__call__</code>方法实现中编写一层函数即可，即<code>__call__</code>方法就是装饰函数。</p>
<p>对于<code>type.__call__(cls, *argv, **kwargs)</code>，除了<code>cls</code>参数以外，其余的参数都会随<code>object.__new__</code>返回的实例化对象一齐传入到相应的<code>__init__</code>方法中，所以我们只需要在<code>__init__</code>方法中处理被装饰函数即可。对应类对象这时候就成为了被装饰函数替代者。</p>
<p>下一章，我们将实现一个经典的类对象装饰器————<strong>property</strong></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2020/04/04/%E6%90%9E%E5%AE%9APython%E8%A3%85%E9%A5%B0%E5%99%A8%EF%BC%88%E4%BA%8C%EF%BC%89/" data-id="ck8swb30n000dwds6ebq4fyux" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/python%E6%95%99%E7%A8%8B/" rel="tag">python教程</a></li></ul>

    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2020/04/04/%E6%90%9E%E5%AE%9APython%E8%A3%85%E9%A5%B0%E5%99%A8%EF%BC%88%E4%B8%89%EF%BC%89%E5%AE%9E%E7%8E%B0property%E7%B1%BB/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          搞定Python装饰器（三）实现property类
        
      </div>
    </a>
  
  
    <a href="/2020/04/04/%E3%80%90%E5%9B%BE%E7%89%87%E6%B5%8B%E8%AF%95%E3%80%91%E5%8F%AF%E7%88%B1%E7%9A%84%E5%90%92%E5%84%BF/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">【图片测试】可爱的吒儿</div>
    </a>
  
</nav>

  
</article>

</section>
        
          <aside id="sidebar">
  
    

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tags</h3>
    <div class="widget">
      <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/tags/SAIL%E5%BC%80%E5%8F%91%E6%97%A5%E5%BF%97/" rel="tag">SAIL开发日志</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/python%E6%95%99%E7%A8%8B/" rel="tag">python教程</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E5%93%AA%E5%90%92%E7%9B%B8%E5%85%B3/" rel="tag">哪吒相关</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E6%B5%81%E6%B0%B4%E8%B4%A6/" rel="tag">流水账</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E8%8A%B1%E9%87%8C%E8%83%A1%E5%93%A8/" rel="tag">花里胡哨</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget tagcloud">
      <a href="/tags/SAIL%E5%BC%80%E5%8F%91%E6%97%A5%E5%BF%97/" style="font-size: 10px;">SAIL开发日志</a> <a href="/tags/python%E6%95%99%E7%A8%8B/" style="font-size: 20px;">python教程</a> <a href="/tags/%E5%93%AA%E5%90%92%E7%9B%B8%E5%85%B3/" style="font-size: 10px;">哪吒相关</a> <a href="/tags/%E6%B5%81%E6%B0%B4%E8%B4%A6/" style="font-size: 15px;">流水账</a> <a href="/tags/%E8%8A%B1%E9%87%8C%E8%83%A1%E5%93%A8/" style="font-size: 10px;">花里胡哨</a>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/04/">April 2020</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2020/04/05/%E3%80%90LaTeX%E6%B5%8B%E8%AF%95%E3%80%91%E4%B8%80%E4%BA%9B%E8%91%97%E5%90%8D%E7%9A%84%E5%85%AC%E5%BC%8F/">【LaTeX测试】一些著名的公式</a>
          </li>
        
          <li>
            <a href="/2020/04/04/%E6%90%9E%E5%AE%9APython%E8%A3%85%E9%A5%B0%E5%99%A8%EF%BC%88%E4%B8%89%EF%BC%89%E5%AE%9E%E7%8E%B0property%E7%B1%BB/">搞定Python装饰器（三）实现property类</a>
          </li>
        
          <li>
            <a href="/2020/04/04/%E6%90%9E%E5%AE%9APython%E8%A3%85%E9%A5%B0%E5%99%A8%EF%BC%88%E4%BA%8C%EF%BC%89/">搞定Python装饰器（二）</a>
          </li>
        
          <li>
            <a href="/2020/04/04/%E3%80%90%E5%9B%BE%E7%89%87%E6%B5%8B%E8%AF%95%E3%80%91%E5%8F%AF%E7%88%B1%E7%9A%84%E5%90%92%E5%84%BF/">【图片测试】可爱的吒儿</a>
          </li>
        
          <li>
            <a href="/2020/04/03/%E6%90%9E%E5%AE%9APython%E8%A3%85%E9%A5%B0%E5%99%A8%EF%BC%88%E4%B8%80%EF%BC%89/">搞定 Python 装饰器（一）</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2020 Laomo.<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>
    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>


  
<link rel="stylesheet" href="/fancybox/jquery.fancybox.css">

  
<script src="/fancybox/jquery.fancybox.pack.js"></script>




<script src="/js/script.js"></script>




  </div>
</body>
</html>